package edu.hrbeu.crc.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Data
@Configuration
public class OssConfig {

    /**
     * endpoint
     */
    @Value("${oss.endpoint}")
    private String endpoint;
    /**
     * Bucket 名称
     */
    @Value("${oss.bucket}")
    private String bucket;
    /**
     * 指定上传到 OSS 的文件前缀
     */
    @Value("${oss.dir}")
    private String dir;
    /**
     * 指定过期时间，单位为秒
     */
    @Value("${oss.expireTime}")
    private long expireTime;
    /**
     * 构造 host
     */
    private String host;
    /**
     * 通过环境变量设置 accessKeyId
     */
    private String accessKeyId = System.getenv("OSS_ACCESS_KEY_ID");
    /**
     * 通过环境变量设置 accessKeySecret
     */
    private String accessKeySecret = System.getenv("OSS_ACCESS_KEY_SECRET");

    private OSS ossClient;

    @PostConstruct // 对象构造完成且属性注入后执行
    public void initHost() {
        this.host = "http://" + bucket + "." + endpoint;
    }

    @Bean
    public OSS getOssClient() {
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        return ossClient;
    }
    @Bean
    public String getHost() {
        return host;
    }
    @Bean
    public String getAccessKeyId() {
        return accessKeyId;
    }
    @Bean
    public long getExpireTime() {
        return expireTime;
    }
    @Bean
    public String getDir() {
        return dir;
    }

    @PreDestroy
    public void onDestroy() {
        ossClient.shutdown();
    }
}
